<template>
  <div id="student-table">
    <el-button @click="addStudent">添加</el-button>
    <el-table :data="tableDataList" border>
      <el-table-column label="名称">
        <template slot-scope="scope">
            <!-- 用户下拉框 -->
            <el-select v-show="scope.row.show" v-model="scope.row.studentId"
                       @change="studentListSelect(scope.row.addIndexId,scope.row.studentId,scope.row.id)"
                       filterable placeholder="请选择学生">
              <el-option
                v-for="item in studentList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          <span v-show="!scope.row.show">{{scope.row.studentName}}</span>

        </template>
      </el-table-column>
      <el-table-column label="课程">
        <template slot-scope="scope">

          <!-- 课程下拉框 -->
          <el-select v-show="scope.row.show" v-model="scope.row.courseType"
                     @change="courseListSelect(scope.row.addIndexId,scope.row.courseType,scope.row.id)"
                     filterable placeholder="请选择课程">
            <el-option
              v-for="item in courseList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
<!--          {{scope.row.courseType}}-->
          <span v-show="!scope.row.show">{{scope.row.courseName}}</span>

        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          <el-input placeholder="请输入内容" v-show="scope.row.show" v-model="scope.row.remarks"></el-input>
          <span v-show="!scope.row.show">{{scope.row.remarks}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span v-show="scope.row.show">
                      <el-button @click="saveRecord(scope)" type="primary">保存课程记录</el-button>
          </span>
          <span v-show="!scope.row.show">
            <el-button @click="scope.row.show =true">编辑</el-button>
          </span>
          <el-button @click="deleteAction(scope.row.addIndexId,scope.row.studentName,scope.row.courseName,scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
    import ElementUI from "element-ui";
    import Bus from './bus.js';
    export default {
        name: "student-table",
      // props: {
      //   baseCourseId :{type :String,require: true}
      // },
        data() {
          return {
            //要展示的table数据
            tableDataList: [
              // {id:'1',baseCourseId:"", studentId:"",studentName: '张三', courseType:"3",courseName: '英语', remarks: '',show:false},
              // {id:'2',baseCourseId:"", studentId:"",studentName: '李四', courseType:"4",courseName: '数学', remarks: '' ,show:false},
            ],
            //学生选择框
            studentList: [{
              value: '1',
              label: '刘'
            }, {
              value: '2',
              label: '张三'
            }],
            studentId: '',
            studentName:'',
            addIndexId:0,
            // baseCourseId:'',
            //课程选择框
            courseList: [{
              value: '1',
              label: '英语'
            }, {
              value: '2',
              label: '数学'
            }],
            courseType: '',
            courseName:'',
            baseCourseId:""
          }
        },
      methods :{

        //显示课程选择框的名称
        courseListSelect(addIndexId,courseType,id){
          let courseListData = this.courseList;
          for (let index = 0; index < courseListData.length; index++) {
            let courseData = courseListData[index];
            if(courseData.value == courseType){
              let courseName = courseData.label;
              this.updateCourseRecordList(addIndexId,id,courseType,courseName);
              return;
            }
          }
        },
        //显示学生选择框的名称
        studentListSelect(addIndexId,studentId,id){

          let studentListData = this.studentList;
          for (let index = 0; index < studentListData.length; index++) {
            let studentData = studentListData[index];
            if(studentData.value == studentId){
              let studentName = studentData.label;
              this.updateStudentRecordList(addIndexId,id,studentId,studentName);
              return;
            }
          }

        },
          addStudent(){
          let addIndexId = this.addIndexId;
            addIndexId = addIndexId-1;
            this.addIndexId = addIndexId;

            let data = {addIndexId:addIndexId,
              id:'', baseCourseId:this.baseCourseId,
              baseCourseKey:"",studentId:"",studentName: '',
              courseType:"",courseName: '', remarks: '',show:true};
            this.tableDataList.push(data);

          },

      //删除确认
        deleteAction(addIndexId,studentName,courseName,id) {
          this.$confirm('正在删除('+studentName+'-'+courseName+')  是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteStudent(addIndexId,id)
            // alert(12344);
            // this.$message({
            //   type: 'success',
            //   message: '删除成功!'
            // });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },


        deleteStudent(addIndexId,id) {
          //如果id为空 则使用索引 addIndexId 删除
          if(id==''){
              let tableDataList = this.tableDataList;
                let tableDataListNew = [];
              for (let index = 0; index < tableDataList.length; index++) {
                let tableData = tableDataList[index];
                 if(tableData.addIndexId != addIndexId){
                    tableDataListNew.push(tableData);
                 }
              }
              this.tableDataList = [];
              this.tableDataList = tableDataListNew;
              tableDataList = [];
              tableDataListNew = [];
              return;
            }

          // 根据id删除
          this.$store.dispatch("record/deleteObject", id).then((res) => {
            //刷新数据
            this.selectRecodeById(this.baseCourseId);
            //刷新父级列表
            this.refreshListData();
            ElementUI.Message({
              message: '删除成功',
              type: 'success'
            });
          }).catch((e) => {
            console.log(e)
          });

          //
          // // 根据id删除
          // this.$axios({
          //   method: 'Delete',
          //   url: this.$api.deleteRecordDataURL+id,
          // }).then(res => {
          //   if (res.data.code == 200) {
          //     //刷新数据
          //     this.selectRecodeById(this.baseCourseId);
          //     //刷新父级列表
          //     this.refreshListData();
          //     ElementUI.Message({
          //       message: '删除成功',
          //       type: 'success'
          //     });
          //
          //   }
          // }).catch(error => {
          //   console.log(error)
          // })


        },
        //保存
        saveRecord(scope){
          let sendData = scope.row;
          if(sendData.studentName==null||sendData.studentName==''){
            ElementUI.Message({
              message: '请选择学生',
              type: 'success'
            });
            return;
          }
          if(sendData.courseName==null||sendData.courseName==''){
            ElementUI.Message({
              message: '请选择课程',
              type: 'success'
            });
            return;
          }
          // alert(JSON.stringify(scope.row));
          // alert(JSON.stringify(this.baseCourseId));
          // alert(JSON.stringify(sendData));

          //更新模板数据
          this.$store.dispatch("record/updateObject", sendData).then((res) => {
            //刷新当前页
            this.selectRecodeById(sendData.baseCourseId);
            //刷新父级列表页
            this.refreshListData();
            //改变现实方式
            scope.row.show =false
            ElementUI.Message({
              message: '保存完成',
              type: 'success'
            });
          }).catch((e) => {
            console.log(e)
          });


          // this.$axios({
          //   method: 'post',
          //   url: this.$api.saveRecordDataURL,
          //   data:sendData
          // }).then(res => {
          //   if (res.data.code == 200) {
          //     //刷新当前页
          //     this.selectRecodeById(sendData.baseCourseId);
          //     //刷新父级列表页
          //     this.refreshListData();
          //     //改变现实方式
          //     scope.row.show =false
          //
          //     ElementUI.Message({
          //       message: '保存完成',
          //       type: 'success'
          //     });
          //   }
          // }).catch(error => {
          //   console.log(error)
          // })

        },

        updateStudentRecordList(addIndexId,id,studentId,studentName){
          let tableDataList = this.tableDataList;
          //如果id为空使用索引id更新
          if(id==null||id==''){
            for (let index = 0; index < tableDataList.length; index++) {
              let tableData = tableDataList[index];
              if(tableData.addIndexId == addIndexId){
                tableData.studentId = studentId;
                tableData.studentName = studentName;
                return
              }
            }
          }else {
            //如果id不为空，则使用id更新
            for (let index = 0; index < tableDataList.length; index++) {
              let tableData = tableDataList[index];
              if(tableData.id == id){
                tableData.studentId = studentId;
                tableData.studentName = studentName;
                return
              }
            }
          }

        },

        updateCourseRecordList(addIndexId,id,courseType,courseName){
          let tableDataList = this.tableDataList;
          if(id==null||id==''){
            for (let index = 0; index < tableDataList.length; index++) {
              let tableData = tableDataList[index];
              if(tableData.addIndexId == addIndexId){
                tableData.courseType = courseType;
                tableData.courseName = courseName;
                return
              }
            }
          }else {
            for (let index = 0; index < tableDataList.length; index++) {
              let tableData = tableDataList[index];
              if(tableData.id == id){
                tableData.courseType = courseType;
                tableData.courseName = courseName;
                return
              }
            }
          }

        },
        selectCourseType () {
          const param = {dictType:'course_type'}
          this.$store.dispatch("dist/selectDistType", param).then((res) => {
            // console.log("============2 " + JSON.stringify(this.wordModuleListData))
            // const courseList = this.$store.state.dist.courseList
            if (res != null) {
              this.courseList = []
              this.courseList = res
            }
          }).catch((e) => {
            console.log(e)
          });


        },
        selectStudentList () {
          this.$store.dispatch("dist/selectStudentList").then((res) => {
            // console.log("============2 " + JSON.stringify(this.wordModuleListData))
            // const studentList = this.$store.state.dist.studentList
            if (res != null) {
              this.studentList = []
              this.studentList = res
            }
          }).catch((e) => {
            console.log(e)
          });

        },

        selectRecodeById(baseCourseId){
          this.tableDataList = [];
          const params = {baseCourseId:baseCourseId}
          this.$store.dispatch("record/selectRecodeById", params).then((res) => {
            const recordDataList = res.data;
            if (recordDataList != null) {
              for (let index = 0; index < recordDataList.length; index++) {
                let record = recordDataList[index];
                if (record != null) {
                  const data = {id:record.id,
                    baseCourseId:record.baseCourseId,
                    studentId:record.studentId,
                    studentName: record.studentName,
                    courseType:record.courseType.toString(),
                    courseName: record.courseName,
                    remarks: record.remarks,
                    show:false};
                  // let entity = {"value": student.id, "label": student.studentName};
                  this.tableDataList.push(data);
                  // console.log(JSON.stringify(this.tableDataList));
                }
              }
            }

          }).catch((e) => {
            console.log(e)
          });

          // this.$axios({
          //   method: 'get',
          //   url: this.$api.findRecordDataURL+baseCourseId
          // }).then(res => {
          //   if (res.data.code == 200) {
          //     var recordDataList = res.data.data;
          //     if (recordDataList != null) {
          //       for (let index = 0; index < recordDataList.length; index++) {
          //         let record = recordDataList[index];
          //         if (record != null) {
          //           var data = {id:record.id,
          //                      baseCourseId:record.baseCourseId,
          //                      studentId:record.studentId,
          //                      studentName: record.studentName,
          //                      courseType:record.courseType.toString(),
          //                      courseName: record.courseName,
          //                      remarks: record.remarks,
          //                      show:false};
          //           // let entity = {"value": student.id, "label": student.studentName};
          //           this.tableDataList.push(data);
          //           // console.log(JSON.stringify(this.tableDataList));
          //         }
          //       }
          //     }
          //
          //   }
          // }).catch(error => {
          //   console.log(error)
          // })



        },

        refreshListData(){
          this.$nextTick(function () {
            //更新数据id
            //如 course 执行刷新数据
            Bus.$emit('toCourseRefreshListAction','刷新列表');
          });
        },


      },
      mounted() { //mounted 是vue的生命周期函数中的其中一个，表示，页面加载完毕执行
      },
      created() {
        this.selectCourseType();//筛选课程列表
        this.selectStudentList();//筛选学生列表

        //接收发送过来的数据
        Bus.$off('toBaseCourseIdAction');//防止出现多次调用，在执行的时候需要卸掉
        Bus.$on('toBaseCourseIdAction', baseCourseId => {
          console.log("baseCourseId "+baseCourseId);
          this.baseCourseId = baseCourseId;
          this.selectRecodeById(baseCourseId)
        });

        //筛选学生列表
        Bus.$off('toCourseTableRefreshStudentListAction');//防止出现多次调用，在执行的时候需要卸掉
        Bus.$on('toCourseTableRefreshStudentListAction', data => {
          this.selectStudentList();//筛选学生列表
        });

      }

    }
</script>

<style scoped>

</style>
